/**
 * FIFOFixSizeQueue.java
 */
package com.mht2017.common.dto;

import java.util.ArrayDeque;

import com.alibaba.fastjson.JSON;

/**
 * 存放指定大小的队列，队列满后，会移除最先加入的数字<br/>
 * 移除规则：仅当有新元素加入的时候才触发移除算法
 *
 * @author yutong.xiao
 * @date 2017年3月29日 上午11:02:15
 */
public class FIFOFixSizeQueue {

	private int fixSize;
	private ArrayDeque<Long> deque;

	public FIFOFixSizeQueue(int fixSize) {
		deque = new ArrayDeque<>(fixSize);
		this.fixSize = fixSize;
	}

	public synchronized void add(long e) {
		check();
		deque.addLast(e);
	}

	private void check() {
		final int size = deque.size();
		if (size >= fixSize) {
			deque.removeFirst();
		}
	}

	public synchronized Long[] getAllElements() {
		return deque.toArray(new Long[0]);
	}

	public int getActualSize() {
		return deque.size();
	}

	public int getFixSize() {
		return fixSize;
	}

	public double avg() {
		Long[] all = getAllElements();
		if (null == all) {
			return 0;
		}

		int sum = 0;
		for (Long one : all) {
			sum += null == one ? 0 : one;
		}
		return 1D * sum / all.length;
	}

	@Override
	public String toString() {
		return JSON.toJSONString(this);
	}

}
